package com.example.springbootfirst.configuration;

import cn.hutool.core.collection.CollUtil;
import com.example.springbootfirst.properties.SwaggerProperties;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.function.Predicate;

/**
 * created by Morgan on 2021/10/1
 */
@Configuration
@Slf4j
public class SwaggerConfig {

    @Autowired
    private SwaggerProperties swaggerProperties;

    @Bean
    public Docket docket() {
        Contact contact = new Contact(swaggerProperties.getName(),swaggerProperties.getUrl(),swaggerProperties.getEmail());
        ApiInfo apiInfo = new ApiInfoBuilder().title(swaggerProperties.getTitle()).contact(contact).version(swaggerProperties.getVersion()).build();
        Predicate<RequestHandler> selector = RequestHandlerSelectors.none();
        if (CollUtil.isNotEmpty(swaggerProperties.getBasePackage())) {
            for (String base : swaggerProperties.getBasePackage()) {
                selector = selector.or(RequestHandlerSelectors.basePackage(base));
            }
        }else {
            selector = selector.or(RequestHandlerSelectors.withClassAnnotation(Api.class));
        }
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo)
                .select()
                .apis(selector)
                .paths(PathSelectors.ant("/api/**"))
                .build();
    }
}
